import React from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";

interface ImageUploadProps {
  value?: string;
  onChange: (base64Image: string | null) => void;
}

export const ImageUpload: React.FC<ImageUploadProps> = ({
  value,
  onChange,
}) => {
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        onChange(reader.result as string);
      };
      reader.readAsDataURL(file);
    } else {
      onChange(null);
    }
  };

  const handleClear = () => {
    onChange(null);
  };

  return value ? (
    <div className="flex gap-2">
      <img
        src={value}
        alt="Uploaded Image"
        className="max-w-[150px] max-h-[150px] object-contain border rounded-md"
      />
      <Button
        className="left-0 top-0"
        variant="secondary"
        size="sm"
        onClick={handleClear}
      >
        <X />
      </Button>
    </div>
  ) : (
    <Input type="file" accept="image/*" onChange={handleFileChange} />
  );
};
